package com.lzy.sso.cas.service.impl;

import com.lzy.sso.cas.pojo.Identification;
import com.lzy.sso.cas.principle.Principle;
import com.lzy.sso.cas.service.AbstractAuthenticationService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: lzy
 * @Date: 2022/4/25 16:39
 * @Description: 处理session认证
 */

//@Service
public class SessionAuthenticationService extends AbstractAuthenticationService {
    /**
     * 注销
     * @param request
     * @param response
     */
    @Override
    public void logout(HttpServletRequest request,HttpServletResponse response) {
        HttpSession session = request.getSession(false);
        if(session!=null){
            session.invalidate();
        }
    }

    /**
     * 是否在登录状态
     * 默认以session是否存在为准
     * 若自定义可以重写该方法
     * 不行我再写个自定义接口
     * @param request
     * @param response
     * @return
     */
    @Override
    public boolean isActive(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession(false);
        if(session!=null){
            return true;
        }
        return false;
    }

    /**
     * 获取认证授权信息
     * @param token
     * @return
     */
    @Override
    public Map<String, Object> getInfo(String token) {
        Map<String,Object> map=new HashMap<>();
        Identification identification=tokenManagement.getIdentification(token);

        map.put("type","session");
        map.put("sessionID",identification.getAttribute("sessionID"));

        Principle principle=identification.getPrinciple();
        map.put("info",principle.getAllBaseInfo());
        map.put("role",principle.getRoles());
        return map;
    }

    /**
     * session方式
     * 生成全局session
     * 添加sessionID到Identification
     * @param request
     * @param response
     * @param token
     * @param identification
     */
    @Override
    protected void doProcess(HttpServletRequest request, HttpServletResponse response, String token, Identification identification) {
        HttpSession session = request.getSession(true);
        String sessionID = session.getId();
        identification.setType("session");

        identification.addAttribute("sessionID",sessionID);
    }
}
